<template>
  <div class="comment-list">
    <div class="comment-header">
      <h3>评论 ({{ comments.length }})</h3>
    </div>
    
    <!-- 评论输入框 -->
    <div class="comment-input-area" v-if="showInput">
      <el-input
        type="textarea"
        v-model="newComment"
        placeholder="请输入您的评论..."
        :rows="3"
        maxlength="500"
        show-word-limit
      />
      <div class="comment-actions">
        <el-button 
          type="primary" 
          @click="submitComment" 
          :loading="submitting"
          :disabled="!newComment.trim()"
        >
          发表评论
        </el-button>
        <el-button @click="cancelComment">取消</el-button>
      </div>
    </div>
    
    <!-- 评论列表 -->
    <div class="comments-container">
      <div v-if="comments.length === 0" class="no-comments">
        暂无评论，快来发表第一条评论吧！
      </div>
      <Comment 
        v-for="comment in comments" 
        :key="comment.id" 
        :comment="comment" 
        class="comment-item"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, defineEmits, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/api/request'
import Comment from './Comment.vue'

interface Comment {
  id: number
  user_nickname?: string
  content: string
  created_at?: string
  comment_time?: string
}

const props = defineProps<{
  moduleId: string
  fid: number
  showInput?: boolean
}>()

const emit = defineEmits(['comment-submitted'])

const comments = ref<Comment[]>([])
const newComment = ref('')
const submitting = ref(false)
const loading = ref(false)

// 获取评论列表
const fetchComments = async () => {
  // 如果 fid 为 0 或无效，不请求评论
  if (!props.fid) {
    comments.value = []
    return
  }
  
  loading.value = true
  try {
    const response: any = await request.get('/health/comments/', {
      params: {
        module: props.moduleId,
        fid: props.fid
      }
    })
    
    // 处理响应数据，兼容分页和非分页格式
    if (response && typeof response === 'object') {
      if (Array.isArray(response)) {
        // 直接返回数组格式
        comments.value = response
      } else if (response.results && Array.isArray(response.results)) {
        // 分页格式
        comments.value = response.results
      } else {
        // 其他格式
        comments.value = []
      }
    } else {
      comments.value = []
    }
  } catch (error) {
    console.error('获取评论失败:', error)
    ElMessage.error('获取评论失败')
    comments.value = []
  } finally {
    loading.value = false
  }
}

// 提交评论
const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容')
    return
  }
  
  if (!props.fid) {
    ElMessage.error('无效的帖子ID')
    return
  }
  
  submitting.value = true
  try {
    const response: any = await request.post('/health/comments/', {
      content: newComment.value,
      module: props.moduleId,
      fid: props.fid
    })
    
    // 添加新评论到列表顶部
    comments.value.unshift(response)
    newComment.value = ''
    ElMessage.success('评论发表成功')
    emit('comment-submitted', response)
  } catch (error: any) {
    ElMessage.error(error.message || '评论发表失败')
  } finally {
    submitting.value = false
  }
}

// 取消评论
const cancelComment = () => {
  newComment.value = ''
}

// 刷新评论列表
const refreshComments = () => {
  fetchComments()
}

// 监听 props 变化
watch(() => [props.moduleId, props.fid], () => {
  fetchComments()
}, { immediate: true })

// 组件挂载时获取评论
onMounted(() => {
  fetchComments()
})

// 暴露方法给父组件
defineExpose({
  refreshComments
})
</script>

<style scoped>
.comment-list {
  margin-top: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 4px;
}

.comment-header h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.comment-input-area {
  margin-bottom: 20px;
}

.comment-actions {
  margin-top: 10px;
  text-align: right;
}

.comments-container {
  min-height: 100px;
}

.no-comments {
  text-align: center;
  color: #999;
  padding: 30px 0;
}

.comment-item {
  margin-bottom: 15px;
}

.comment-item:last-child {
  margin-bottom: 0;
}
</style>